import { Module } from 'vuex'
import {
  SET_USER_INFO,
  LOGIN,
  USER_LOGOUT,
  REGISTER,
  LOGOUT,
} from '../mutations'
import { request } from '@/plugins/http.plugin'
import md5 from 'md5'

const initUserInfo: UserInfoState = {
  UserId: '-1',
  RealName: '',
  Phone: '',
  Age: 0,
  CardNo: '',
  PicUrl: '',
  Sex: 0,
  PersonId: '',
  Token: '-1',
  UserName: '',
  HeadPhoto: '',
  Position: '',
}
const userInfoStorage = 'mUserInfo'
const userInfoStr = localStorage.getItem(userInfoStorage)
const userInfoObj = userInfoStr ? JSON.parse(userInfoStr) : { ...initUserInfo }

const userInfo: Module<UserInfoState, any> = {
  state: userInfoObj,
  mutations: {
    [SET_USER_INFO] (state, payload) {
      Object.assign(state, payload)
      localStorage.setItem(userInfoStorage, JSON.stringify(state))
    },
    [USER_LOGOUT] (state) {
      // localStorage.removeItem(userInfoStorage)
      Object.assign(state, { ...initUserInfo })
    },
  },
  actions: {
    [LOGIN] ({ commit, rootState, dispatch }, { userName, pwd }) {
      return request({
        url: 'ELogin/Login',
        data: {
          LoginName: userName,
          Password: pwd,
        },
      }, { state: rootState, dispatch }, 1).then(res => {
        commit(SET_USER_INFO, {
          ...res,
          UserId: res.Token,
        })
        return {
          ...res,
          UserId: res.Token,
        }
      })
    },
    [LOGOUT] ({ commit }) {
      commit(USER_LOGOUT)
    },
    [REGISTER] ({ commit, rootState, dispatch }, { userName, pwd, key }) {
      return request({
        url: 'ELogin/Register',
        data: {
          MobilePhone: userName,
          Password: pwd,
          InviteCode: key,
        },
      })
    },
    // [ADD_DELETE_CART] ({ commit, rootState, state, dispatch }, {
    //   GoodsId,
    //   Type = 1,
    //   /**
    //    * 增加1，删除-1
    //    */
    //   increaseNum = 1,
    // }) {
    //   return request({
    //     url: `shopping/${increaseNum === 1 ? 'AddShoppingCartForWeb' : 'deleteShoppingCartForWeb'}`,
    //     data: {
    //       Type,
    //       GoodsId,
    //     },
    //   }, { state: rootState, dispatch }).then(res => {
    //     commit(SET_USER_INFO, { ShoppingCount: state.ShoppingCount + increaseNum })
    //     return res
    //   })
    // },
  },
}

export default userInfo
